import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../models/psychological_test.dart';
import '../models/database_helper.dart';
import 'package:intl/intl.dart';
import 'test_report_screen.dart';
import 'package:flutter/services.dart';

class TestHistoryScreen extends StatefulWidget {
  final TestType? testType;
  
  const TestHistoryScreen({
    Key? key,
    this.testType,
  }) : super(key: key);

  @override
  State<TestHistoryScreen> createState() => _TestHistoryScreenState();
}

class _TestHistoryScreenState extends State<TestHistoryScreen> {
  List<TestRecord> records = [];
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadRecords();
  }

  Future<void> _loadRecords() async {
    final db = DatabaseHelper.instance;
    final loadedRecords = widget.testType != null
        ? await db.getTestRecordsByType(widget.testType!)
        : await db.getAllTestRecords();
    setState(() {
      records = loadedRecords;
      isLoading = false;
    });
  }

  Future<void> _deleteRecord(TestRecord record) async {
    try {
      if (record.id == null) {
        throw Exception('记录ID为空');
      }
      await DatabaseHelper.instance.deleteTestRecord(record.id!);
      setState(() {
        records.removeWhere((r) => r.id == record.id);
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('删除失败，请重试')),
        );
      }
    }
  }

  void _showDeleteDialog(TestRecord record) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(
          '确认删除',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            color: Colors.black87,
          ),
        ),
        content: Text(
          '确定要删除这条测试记录吗？',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 16,
            color: Colors.black54,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              '取消',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 16,
                color: Colors.black54,
              ),
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _deleteRecord(record);
            },
            child: Text(
              '删除',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 16,
                color: Colors.red,
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _getTestTypeName(TestType type) {
    switch (type) {
      case TestType.SDS:
        return 'SDS历史报告';
      case TestType.SAS:
        return 'SAS历史报告';
      case TestType.SCL90:
        return 'SCL-90历史报告';
    }
  }

  String _getTestName(TestType type) {
    switch (type) {
      case TestType.SDS:
        return '抑郁自评量表(SDS)';
      case TestType.SAS:
        return '焦虑自评量表(SAS)';
      case TestType.SCL90:
        return '症状自评量表(SCL-90)';
    }
  }

  Color _getTestTypeColor(TestType type) {
    switch (type) {
      case TestType.SDS:
        return const Color(0xFF2196F3); // 蓝色
      case TestType.SAS:
        return const Color(0xFF9C27B0); // 紫色
      case TestType.SCL90:
        return const Color(0xFFFF9800); // 橙色
    }
  }

  String _getScoreLevel(TestType type, double score) {
    if (type == TestType.SCL90) {
      if (score < 1.5) return '正常范围';
      if (score < 2.5) return '轻度';
      return '中度';
    } else if (type == TestType.SDS) {
      if (score < 50) return '正常范围';
      if (score < 60) return '轻度抑郁';
      if (score < 70) return '中度抑郁';
      return '重度抑郁';
    } else {
      if (score < 50) return '正常范围';
      if (score < 60) return '轻度焦虑';
      if (score < 70) return '中度焦虑';
      return '重度焦虑';
    }
  }

  String _getScoreLevelDescription(TestType type) {
    if (type == TestType.SCL90) {
      return '正常范围          轻度          中度';
    } else if (type == TestType.SDS) {
      return '正常范围          轻度抑郁          中度抑郁          重度抑郁';
    } else {
      return '正常范围          轻度焦虑          中度焦虑          重度焦虑';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          widget.testType != null 
              ? _getTestTypeName(widget.testType!)
              : '历史报告',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: records.length,
              itemBuilder: (context, index) {
                final record = records[index];
                final score = record.testType == TestType.SCL90
                    ? record.answers.reduce((a, b) => a + b) / 90
                    : record.standardScore;
                final color = _getTestTypeColor(record.testType);
                final level = _getScoreLevel(record.testType, score);

                return GestureDetector(
                  onLongPress: () {
                    HapticFeedback.mediumImpact();
                    _showDeleteDialog(record);
                  },
                  child: Container(
                    margin: const EdgeInsets.only(bottom: 16),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(15),
                      border: Border.all(color: Colors.grey.shade200),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    _getTestName(record.testType),
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  Text(
                                    DateFormat('yyyy年MM月dd日').format(record.testDate),
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 14,
                                      color: Colors.black54,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Text(
                                    record.testType == TestType.SCL90 ? '总均分' : '标准分',
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 16,
                                      color: Colors.black54,
                                    ),
                                  ),
                                  const Spacer(),
                                  Text(
                                    record.testType == TestType.SCL90
                                        ? score.toStringAsFixed(2)
                                        : score.toStringAsFixed(0),
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 24,
                                      fontWeight: FontWeight.bold,
                                      color: color,
                                    ),
                                  ),
                                  Text(
                                    ' 分',
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 16,
                                      color: Colors.black54,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 8),
                              Stack(
                                children: [
                                  Container(
                                    width: double.infinity,
                                    height: 4,
                                    decoration: BoxDecoration(
                                      color: Colors.grey[100],
                                      borderRadius: BorderRadius.circular(2),
                                    ),
                                  ),
                                  FractionallySizedBox(
                                    widthFactor: record.testType == TestType.SCL90
                                        ? score / 4
                                        : score / 100,
                                    child: Container(
                                      height: 4,
                                      decoration: BoxDecoration(
                                        color: color.withOpacity(0.8),
                                        borderRadius: BorderRadius.circular(2),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 10),
                              Text(
                                _getScoreLevelDescription(record.testType),
                                style: GoogleFonts.zcoolKuaiLe(
                                  fontSize: 13,
                                  color: Colors.black54,
                                  height: 1.2,
                                ),
                              ),
                              const SizedBox(height: 16),
                              SizedBox(
                                width: double.infinity,
                                child: TextButton(
                                  onPressed: () {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => TestReportScreen(record: record),
                                      ),
                                    );
                                  },
                                  style: TextButton.styleFrom(
                                    padding: const EdgeInsets.symmetric(vertical: 12),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(20),
                                      side: BorderSide(color: color),
                                    ),
                                  ),
                                  child: Text(
                                    '查看详情',
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 16,
                                      color: color,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
    );
  }
} 